import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { User } from '../../../system/model/user.model';
import { Message } from '../../../share/model/message.model';
import { NoticeService } from '../../../share/service/notice.service';

@Injectable()
export class LoginService {

    private loginCount = 0;

    public redirectUrl: string;             // 重定向路由

    public isLoggedIn: boolean = null;      // 缓存登录状态

    private _userInfo: User = new User();   // 缓存登录人信息，也可能是登录失败信息

    get userInfo() {
        return this._userInfo;
    }

    constructor(private http: HttpClient, private noticeService: NoticeService) { }

    autoLogin(callback: any) {
        this.http.get('system/login').toPromise()
            .then(response => {
                let msg = this.success(response);
                if (typeof callback === 'function') {
                    callback(msg);
                }
            }).catch(error => { this.loginCount++; });
    }

    /**
     * 发送登录请求
     */
    public login(userName, password, callback: any) {
        let authorization = 'Basic ' + btoa(userName + ':' + password);
        let httpHeaders = new HttpHeaders().set('Authorization', authorization);
        this.http.get('system/login', { headers: httpHeaders }).toPromise()
            .then(response => {
                let msg = this.success(response);
                console.log('success', msg);
                if (typeof callback === 'function') {
                    callback(msg);
                }
            }).catch(error => {
                let msg = this.error(error);
                console.log('error', msg);
                if (typeof callback === 'function') {
                    callback(msg);
                }
            });
    }

    /**
     * 正确处理
     * @param response
     *        http请求响应
     */
    private success(response): any {
        let msg = response as Message;
        if (response.errorCode === 0) {
            this.saveLoginInfo(msg.data);
            return { success: true, msg: '登录成功' };
        } else {
            return { success: false, msg: msg.errorMsg };
        }
    }

    /**
     * 错误处理
     */
    private error(error: any): any {
        switch (error.status) {
            case 401:
                return { success: false, msg: '用户名或密码错误' };
            case 500:
                return { success: false, msg: '系统错误，请稍候再试' };
            default:
                return { success: false, msg: '网络异常，请稍候再试' };
        }
    }


    /**
     * 退出
     */
    logout(): void {
        this.http.get('system/logout').toPromise().then(response => {
            this.clearLoginInfo();
        }).catch(error => {
            if (error.status === 200) {
                return;
            }
            if (error.status === 500) {
                this.noticeService.error('系统错误，请稍候再试');
            } else {
                this.noticeService.error('网络异常，请稍候再试');
            }
        });
    }

    /**
     * 添加登录缓存
     * @param data 登录返回的用户信息，json格式的数据
     */
    public saveLoginInfo(data: any): void {
        this.isLoggedIn = true;
        this._userInfo.setDataValue(data);
    }

    /**
     * 清理缓存
     */
    private clearLoginInfo(): void {
        this.isLoggedIn = null;
        this._userInfo = null;
    }

}
